/**
 * @author SilverBiology, LLC
 * @website http://code.google.com/p/gbif-spreadsheet-processor/
*/
Ext.namespace('GBIF');
Ext.namespace('GBIF.GeoSpatial', 'Config.GBIF.GeoSpatial.AvailableLayersTree')

GBIF.GeoSpatial.AvailableLayersTree = function(config){

	Ext.getUrlParam = function(param) {
		var params = Ext.urlDecode( location.search.substring(1) );
		return param ? params[param] : params;
	}; 		
					
	var availableLayers = Ext.getUrlParam('availableLayers');
		
	if (Ext.isEmpty( availableLayers )){
		availableLayers = Config.GBIF.GeoSpatial.AvailableLayersTree.availableLayers || {};
	}

	Ext.apply(this, config, {
			useArrows: Config.GBIF.GeoSpatial.AvailableLayersTree.useArrows
		,	border:	false
		,	root: new Ext.tree.AsyncTreeNode({
					text: 'Layers'
				,	draggable: false
				,	layer: ''
				,	expanded: config.rootExpanded || false
				,	rootVisible: config.rootVisible || false
			})
		,	animate: Config.GBIF.GeoSpatial.AvailableLayersTree.animate	
		,	cls: Config.GBIF.GeoSpatial.AvailableLayersTree.cls
		,	plugins: new Ext.ux.DataTip({
				tpl: new Ext.XTemplate(
					'<div>'+
							'<tpl if="mType != 0">'+
								'Layer Type: {mType} '+
							'</tpl>'+
							'<tpl if="description != 0">'+
								'<br/>Description: {description}'+
							'</tpl>'+	
							'<tpl if="typeof(onlineResource) != \'undefined\'"'+
								'<br/><br/><br/> Right click to view Online Resource'+
							'</tpl>'+
					 '</div>'
					, {
							isDefined: function( value ) {
//								console.log(value);
//								return("test");
							}
						}
				)
			})
		,	listeners: {
				contextmenu: this.nodecontextmenu
			}
		,	loader: config.loader || new Ext.tree.TreeLoader({
					dataUrl: Config.General.Home.url + 'json/' + availableLayers
				,	baseAttrs: {
						uiProvider: Ext.tree.TriStateNodeUI
					}
				,	createNode: function(attr) {
						if ( config.checkboxdisabled ) {
							attr.checked = undefined;
						}
						return Ext.tree.TreeLoader.prototype.createNode.apply(this, [attr]);
					}
				,	listeners: {
							beforeload: this.testNodeUri
						,	scope: this
					}
			})
	});

	GBIF.GeoSpatial.AvailableLayersTree.superclass.constructor.call(this, config);
}

Ext.extend(GBIF.GeoSpatial.AvailableLayersTree, Ext.tree.TreePanel, {

		testNodeUri: function( loader, node ) {
			
			switch( node.attributes.type ) {
				case 'gbif.clb':
					loader.baseParams={
							id: node.attributes.taxonID
						,	rank: node.attributes.rank
					};
					loader.dataUrl = Config.General.Home.url + 'api/gbif-clb-proxy.php';
					loader.processResponse = this.extensionsResponse;
					break;
			
				case 'birdlife':
					switch( node.text ) {
						case 'Families':
							loader.baseParams = {
									type:'family'
								,	value:'all'
							};	
							break;
	
						case 'IUCN Redlist':
							loader.baseParams = {
									type:'iucn'
								,	value:'all'
							};
							break;
	
						default:
							loader.baseParams = {
									type: node.attributes.nType
								,	value: node.attributes.id
							};
							break;
					}
				
					loader.dataUrl = Config.General.Home.url + 'api/birdlife.php';
					loader.processResponse = this.birdlifeResponse;
					break;
			}
		}
		
		/*
		*	This maps the nodes from the json file
		*/
	,	extensionsResponse: function(response, node, callback){
			var json = Ext.decode( response.responseText );
			try {
				o = json.data;
				node.beginUpdate();
				for (var i = 0, len = o.length; i < len; i++) {
					var n = this.createNode(o[i]);
					n.text = o[i].scientificName;
					n.id = o[i].scientificName;
					n.attributes.type = 'gbif.clb';
					n.attributes.taxonID = o[i].taxonID;
					n.attributes.datasetID = o[i].datasetID;
					n.attributes.higherTaxonID = o[i].higherTaxonID;
					n.attributes.nameID = o[i].nameID;
					n.attributes.scientificName = o[i].scientificName;
					n.attributes.rank = o[i].rank;
//						if (o[i].rank == 'kingdom' || o[i].rank == 'species'){
							n.attributes.checked = false;
//						}
					n.attributes.isSynonym = o[i].isSynonym;
					n.attributes.taxonomicStatus = o[i].taxonomicStatus;
					n.attributes.numChildren = o[i].numChildren;
					n.attributes.mType='wms';
					n.attributes.description = ''					
					n.attributes.layer = {
							'layers': 'geobon_tax_occurrence' //o[i].scientificName
						,	'name':o[i].scientificName
						,	'url':'http://ogc.gbif.org/wms'
						,	'opacity': 0.5 
						,	'transparent': true
						,	'FORMAT':"image/jpeg"
						,	'version':"1.1.0"
						,	'f': "image"
						,	'querable':true
						,	'CQL_FILTER' : o[i].rank + "='"+ o[i].scientificName +"'"
						,	'downloadFormats': {
									'Image' : true
								,	'CSV' : false
								,	'GML2' : false
								,	'GML2GZIP' : false	
								,	'GeoJSON' : false
								,	'Shapefile' : true
							}
						,	'columns': [
									{header: "ID", width: 250, dataIndex:"fid", id:'fid'}
								, {header: "Count",dataIndex:"count"}
							]
						,	'fields': [
									{name:'fid',type:'string', mapping:'attributes.fid'}
								,	{name:'count',type:'string'}
								,	{name:'id',type:'string'}
								,	{name: "providername",type:"string"}
								,	{name: "resourcename",type:"string"}
								,	{name: "institutioncode",type:"string"}
								,	{name: "collectioncode",type:"string"}
								,	{name: "catalognumber",type:"string"}
								,	{name: "kingdom",type:"string"}
								,	{name: "phylum",type:"string"}
								,	{name: "class",type:"string"}
								,	{name: "order",type:"string"}
								,	{name: "family",type:"string"}
								,	{name: "genus",type:"string"}
								,	{name: "scientificname",type:"string"}
								,	{name: "decimallatitude",type:"string"}
								,	{name: "decimallongitude",type:"string"}
								,	{name: "minimumelevationinmeters",type:"string"}
								,	{name: "minimumdepthinmeters",type:"string"}
								,	{name: "basisofrecord",type:"string"}
								,	{name: "datelastmodified",type:"string"}
								,	{name: "collector",type:"string"}
								,	{name: "stateprovince",type:"string"}
								,	{name: "locality",type:"string"}
								,	{name: "linkdataportal",type:"string"}
							]
						,	'zoomcolumns': [
									{header: "Fid",dataIndex:"fid", id:'fid'}
								, {header: "Id",dataIndex:"id"}
								,	{header: "Providername",dataIndex:"providername"}
								,	{header: "Resourcename",dataIndex:"resourcename"}
								,	{header: "Institutioncode",dataIndex:"institutioncode"}
								, {header: "Collectioncode",dataIndex:"collectioncode"}
								,	{header: "Catalognumber",dataIndex:"catalognumber"}
								, {header: "kingdom",dataIndex:"kingdom"}
								,	{header: "Phylum",dataIndex:"phylum"}
								, {header: "Class",dataIndex:"class"}
								, {header: "order",dataIndex:"order"}
								,	{header: "family",dataIndex:"family"}
								, {header: "genus",dataIndex:"genus"}
								,	{header: "scientificname",dataIndex:"scientificname"}
								, {header: "decimallatitude",dataIndex:"decimallatitude"}
								,	{header: "decimallongitude",dataIndex:"decimallongitude"}
								, {header: "minimumelevationinmeters",dataIndex:"minimumelevationinmeters"}
								, {header: "minimumdepthinmeters",dataIndex:"minimumdepthinmeters"}
								, {header: "basisofrecord",dataIndex:"basisofrecord"}
								,	{header: "datelastmodified",dataIndex:"datelastmodified"}
								, {header: "collector",dataIndex:"collector"}
								, {header: "stateprovince",dataIndex:"stateprovince"}
								, {header: "locality",dataIndex:"locality"}
								,	{header: "linkdataportal",dataIndex:"linkdataportal"}
							]
					};
										
					if (o[i].numChildren == 0){
						n.leaf=true;
					} else {
						n.leaf=false;
					}
					n.attributes.numDescendants=o[i].numDescendants;
					n.attributes.rating=o[i].rating;
						
					if (n) {
						node.appendChild(n);
					}
				}
				node.endUpdate();
				if (typeof callback == "function") {
					callback(this, node);
				}
			} catch (e) {
				GBIF.GeoSpatial.Notice.msg(this.txtError, this.txtErrorMsg);
			}
		}
		
		/*
		*	
		*/
	,	birdlifeResponse: function(response, node, callback){
			var json = response.responseText;
			try {
				var o = eval("(" + json + ")");
				o = o.data;
				node.beginUpdate();
				for (var i = 0, len = o.length; i < len; i++) {
					var n = this.createNode(o[i]);
					n.text = o[i].text;
					n.id = o[i].text;
					n.specid = o[i].id;
					n.iucn = o[i].iucn;
					n.leaf=o[i].leaf;
					n.attributes.mType = 'wms';
					n.attributes.nType = node.attributes.nType//'family'//type;
					n.attributes.description = '';
					n.attributes.type = 'birdlife';
					if (o[i].checked == false) {
						n.attributes.layer = {
								layers: 'birdlife:gtbs' //o[i].scientificName
							,	name: o[i].text
							,	url: 'http://birdlaa2.memset.net:8080/geoserver/wms'
							,	opacity: 0.5 
							,	filter: '(<Filter xmlns=\"http://www.opengis.net/ogc\"\><PropertyIsEqualTo\><PropertyName\>spcrecid</PropertyName\><Literal\>'+ o[i].id +'</Literal\></PropertyIsEqualTo\></Filter\>)' // 3353
							,	transparent: true
							,	FORMAT:"image/jpeg"
							,	version: "1.1.0"
							,	f: "image"
							,	querable: false
							,	type: 'birdlife'
						}	
					} else {
						n.attributes.layer = '';
					}
								
					if (n) {
						node.appendChild(n);
					}
				}

				node.endUpdate();
				if (typeof callback == "function") {
					callback(this, node);
				}
			} catch (e) {
				GBIF.GeoSpatial.Notice.msg(this.txtError, this.txtErrorMsg);
			}
		}

	,	nodecontextmenu: function(node){
//console.log("node", node);
			node.select();
			this.fireEvent("click", node);
			
			if ( Ext.isDefined(node.attributes.onlineResource) ) {
				
				var menu = new Ext.menu.Menu();
	
				menu.add({
						text: "View Online Resource"
					,	scope: node
					,	handler: function() {
							window.open(this.attributes.onlineResource, '_blank');
						}
				});
				
				menu.show( node.ui.getAnchor() );
			}
		}

});